package threadpool;

import java.util.ArrayList;
import java.util.concurrent.*;

/**
 * @author sjw
 * @className ExecutorCompletion
 * @date 2022/5/5 10:13
 * @description: TODO
 */
public class ExecutorCompletion {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        fun2();
    }

    public  static  void fun1() throws ExecutionException, InterruptedException {
        ExecutorService executorService= Executors.newCachedThreadPool();
        ArrayList<Future<String>> futures=new ArrayList<>();
        System.out.println("开始做饭");
        Future<String> future1= executorService.submit(()->{
            System.out.println("去超市买菜");
            Thread.sleep(10*1000);
            System.out.println("买菜结束，来接吧");
            return "买菜结束";
        });
        futures.add(future1);
        Future<String> future2= executorService.submit(()->{
            System.out.println("去超市买肉");
            Thread.sleep(5*1000);
            System.out.println("买肉结束，来接吧");
            return "买肉结束";
        });
        futures.add(future2);
        Thread.sleep(1*1000);
        System.out.println("等待!!!!");

        for(Future<String> future  :futures){
            String s=future.get();
            System.out.println(s);
        }

        Thread.currentThread().join();
    }


    public  static  void fun2() throws ExecutionException, InterruptedException {
        ExecutorService executorService= Executors.newCachedThreadPool();
        ExecutorCompletionService<String> executorCompletionService=new ExecutorCompletionService(executorService);
        ArrayList<Future<String>> futures=new ArrayList<>();
        System.out.println("开始做饭");
        executorCompletionService.submit(()->{
            System.out.println("去超市买菜");
            Thread.sleep(10*1000);
            System.out.println("买菜结束，来接吧");
            return "买菜结束";
        });
        executorCompletionService.submit(()->{
            System.out.println("去超市买肉");
            Thread.sleep(5*1000);
            System.out.println("买肉结束，来接吧");
            return "买肉结束";
        });
        Thread.sleep(1*1000);
        System.out.println("等待!!!!");

        for(int i=0; i<2;i++){
            String s=executorCompletionService.take().get();
            System.out.println(s+" 去接你");
        }
        System.out.println("123");
        executorService.shutdown();
        // Thread.currentThread().join();
    }
}
